package com.zhang.boot.core.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhang.boot.core.entity.Role;
import com.zhang.boot.core.entity.UserRole;
import com.zhang.boot.core.mapper.RoleMapper;
import com.zhang.boot.core.service.RoleService;
import com.zhang.boot.core.service.UserRoleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
@RequiredArgsConstructor
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    private final UserRoleService userRoleService;

    @Override
    public Role getByRoleName(String roleName) {
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Role::getRoleName, roleName);
        return getOne(queryWrapper);
    }

    @Override
    public List<Role> listByUserId(Integer userId) {
        List<Role> roleList = new ArrayList<>();
        if (userId == null || userId <= 0) {
            return roleList;
        }
        List<UserRole> userRoles = userRoleService.listByUserId(userId);
        if (CollUtil.isEmpty(userRoles)) {
            return roleList;
        }
        List<Integer> roleIdList = userRoles.stream()
                .map(UserRole::getRoleId)
                .collect(Collectors.toList());
        List<Role> roleList1 = new ArrayList<>();
                try {
                    roleList1 = listByIds(roleIdList);
                } catch (Exception e) {
                    e.printStackTrace();
                }
        return roleList1;
    }
}
